<script setup>
import { nextTick, onMounted, onBeforeMount, onBeforeUnmount, onUnmounted, reactive, ref, watch } from 'vue'
import { useTokenStore } from '@/store/token.js' // 导入token状态
import { useUserInfoStore } from '@/store/userInfo.js' // 导入user状态
import { useRouter, useRoute } from 'vue-router'
import { forumBoard1Service } from '@/api/forumBoard'
import { postArticleService, getForumArticleDetailForUpdate, updateArticleService } from '@/api/forumArticle'
import { getCurrentInstance } from "vue"
import MarkdownEditor from '@/components/MarkdownEditor.vue'
import HtmlEditor from '@/components/HtmlEditor.vue'
import MarkdownEditorV3 from '@/components/MarkdownEditorV3.vue'
import { useUserUpdateArticleIdStore } from '@/store/updateArticleId';

const useUpdateArticleIdStore = useUserUpdateArticleIdStore()

const { proxy } = getCurrentInstance(); // 获取全局注册的组件

const router = useRouter();
const route = useRoute();

// 调用useTokenStore得到状态
const tokenStore = useTokenStore();
// 调用useUserInfoStore得到状态
const userInfoStore = useUserInfoStore();

// 是要更新文章还是要发表文章(0：发表文章(默认)。1：更新文章)
const editOrPostTag = ref(0)

// 加载效果
const loadingRequest = ref(false)

const formData = ref({})
const formDataRef = ref()
const rules = {
  title: [
    { required: true, message: "请输入文章标题", trigger: 'blur' },
  ],
  boardIds: [
    { required: true, message: "请输入文章所属板块", trigger: 'blur' },
  ],
  content: [
    { required: true, message: "请输入文章内容", trigger: 'blur' },
  ],
}

// MarkdownEditorV3对象
const MarkdownEditorV3Ref = ref(null);

// 切换编辑器（默认1：Markdown编辑器，0：富文本编辑器）
const editorType = ref(1)
const changeEditorType = () => {
  proxy.Confirm("切换编辑器会清空当前正在编辑的内容，是否确定切换？", () => {
    editorType.value = editorType.value == 0 ? 1 : 0
    formData.value.content = null
  })
}

// 板块信息设置
const boardProps = {
  mutiple: false, // 是否多选
  checkStrictly: true, // 是否严格的遵守父子节点不互相关联
  label: "boardName",
  value: "boardId",
}
// 获取板块信息
const boardList = ref([])
const getBoardList = async () => {
  let result = await forumBoard1Service()
  console.log("获取一级板块及对应的二级板块：", result.data)
  boardList.value = result.data
}

// 发送文章封面
const coverImg = ref(null)
const selectImg = (file) => {
  // 这里我们只需要file中的.file属性
  file = file.file

  // 显示文件
  coverImg.value = URL.createObjectURL(file)

  // 添加到form中
  formData.value.coverImg = file
}
// 取消上传的文章封面图片
const cancelSelectImg = (e) => {
  coverImg.value = null
  formData.value.coverImg = null
}

// 发送文章附件
const attachmentName = ref()
const selectAttachment = (file) => {
  attachmentName.value = file.file.name

  // 这里我们只需要file中的.file属性
  file = file.file

  // 创建文件流
  formData.value.attachmentFile = file

  // 设置文章附件下载所需积分
  formData.value.integral = 0
}
// 删除文章附件
const removeAttachment = () => {
  attachmentName.value = null
  formData.value.attachmentFile = null
}

// 若想修改文章则获取Store中携带的文章ID ---------------------------------------------------------
const getArticleDetail = () => {

  // 先等所有dom加载完
  nextTick(async () => {
    // 清空表单
    formDataRef.value.resetFields()

    // 修改文章
    // 先获取文章详情
    let result = await getForumArticleDetailForUpdate({
      articleId: useUpdateArticleIdStore.getArticleId()
    })
    console.log("我们想修改文章，文章详情", result.data)
    formData.value = result.data.forumArticle

    // 如果当前文章有附件，则回显
    if (result.data.forumArticleAttachmentList) {
      attachmentName.value = result.data.forumArticleAttachmentList[0].fileName
    }

    // 将获取到的文章详情回显到页面中（调用子级方法）
    if (MarkdownEditorV3Ref.value) {
      MarkdownEditorV3Ref.value.updateText(formData.value.markdownContent)
    }

    // 修改编辑器格式：0为富文本编辑器，1为Markdown编辑器
    editorType.value = formData.value.editorType

    // 设置板块信息
    formData.value.boardIds = []
    if (formData.value.parentBoardId) {
      formData.value.boardIds.push(formData.value.parentBoardId)
    }
    if (formData.value.boardId) {
      formData.value.boardIds.push(formData.value.boardId)
    }

    // 设置文章主题和代码主题
    formData.value.previewTheme = result.data.previewTheme
    formData.value.codeTheme = result.data.codeTheme
    // 将获取到的文章主题和代码主题回显到页面中（调用子级方法）
    if (MarkdownEditorV3Ref.value) {
      MarkdownEditorV3Ref.value.updatePreviewTheme(formData.value.previewTheme)
      MarkdownEditorV3Ref.value.updateCodeTheme(formData.value.codeTheme)
    }

    // 设置文章封面
    if (formData.value.cover) {
      coverImg.value = formData.value.cover
    }
  })
}

// 设置markdown编辑器中对应的富文本内容
const setHtmlContent = (htmlContent) => {
  formData.value.content = htmlContent
}
// 设置markdown编辑器的预览主题
const setPreviewTheme = (previewTheme) => {
  console.log(previewTheme)
  formData.value.previewTheme = previewTheme
}
// 设置markdown编辑器的代码主题
const setCodeTheme = (codeTheme) => {
  console.log(codeTheme)
  formData.value.codeTheme = codeTheme
}

// 显示发表文章Dialog -------------------------------------
const showPostDialog = ref(false)
// 显示发表文章前的相关信息
const handleShowPostFialog = () => {
  showPostDialog.value = true
  // 调用MarkdownEditorV3对象中的方法，将文章内容赋值给formData
  if (MarkdownEditorV3Ref.value) {
    MarkdownEditorV3Ref.value.updateContent()
    formData.value.previewTheme = MarkdownEditorV3Ref.value.updatePreviewTheme()
    formData.value.codeTheme = MarkdownEditorV3Ref.value.updateCodeTheme()
  }
}
// 关闭发表文章框
const handleClosePostDialog = () => {
  showPostDialog.value = false
}
// 发表文章
const postArticle = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return
    }

    // 设置板块ID（这里的boardIds为数组，需处理）
    if (formData.value.boardIds.length == 1) {
      // 若只有一级标题
      formData.value.parentBoardId = formData.value.boardIds[0]
      formData.value.boardId = 0
      formData.value.boardName = null
      for (let i = 0; i < boardList.value.length; i++) {
        if (boardList.value[i].boardId == formData.value.parentBoardId) {
          formData.value.parentBoardName = boardList.value[i].boardName
        }
      }
    } else if (formData.value.boardIds.length == 2) {
      // 同时有一级标题和二级标题
      formData.value.parentBoardId = formData.value.boardIds[0]
      formData.value.boardId = formData.value.boardIds[1]
      for (let i = 0; i < boardList.value.length; i++) {
        if (boardList.value[i].boardId == formData.value.parentBoardId) {
          formData.value.parentBoardName = boardList.value[i].boardName
        }
        if (boardList.value[i].children != null) {
          for (let j = 0; j < boardList.value[i].children.length; j++) {
            if (boardList.value[i].children[j].boardId == formData.value.boardId) {
              formData.value.boardName = boardList.value[i].children[j].boardName
            }
          }
        }
      }
    }

    // 删除掉boardIds
    // delete formData.value.boardIds

    // 设置编辑器类型
    formData.value.editorType = editorType.value

    // 获取内容
    const contentText = formData.value.content.replace(/<(?!img).*?>/g, "")
    if (contentText == "") {
      proxy.Notification.warning("正文不能为空")
      return
    }

    // 获取文章标题
    if (formData.value.title == "" || formData.value.title == null) {
      proxy.Notification.warning("文章标题不能为空")
      return
    }

    // 获取附件
    if (attachmentName.value != null) {
      formData.value.attachmentStatus = 1
    } else {
      formData.value.attachmentStatus = 0
    }

    // 请求后端
    console.log("准备好的请求参数，处理后为：", formData.value)
    // 是要更新文章还是要发表文章(0：发表文章(默认)。1：更新文章)
    // const editOrPostTag = ref(0)
    // 开始加载
    let result = null
    try {
      loadingRequest.value = true
      if (editOrPostTag.value == 0) { // 发表文章
        result = await postArticleService(formData.value)
      } else { // 更新文章
        result = await updateArticleService(formData.value)
      }
    } finally {
      loadingRequest.value = false
    }

    console.log("结果", result.data)

    // 弹窗提示“文章发表成功”
    // proxy.Notification.success("文章发表成功")

    // 路由跳转到文章详情
    router.push("/article/detail/" + result.data.articleId)
  })
}

// 返回主页
const toHome = () => {
  router.push(`/userCenter/${userInfoStore.getUserInfo().userId}`)
}

// 编辑器的高度
// const w = ref(window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth)
const markdownEditorHeight = ref(window.innerHeight - 65)
const HtmlEditorHeight = ref(window.innerHeight - 170)
const markdownEditorV3Height = ref(window.innerHeight - 70)

// 时刻监听当前视口宽高
window.addEventListener('resize', function () {
  markdownEditorHeight.value = window.innerHeight - 65
  HtmlEditorHeight.value = window.innerHeight - 170
  markdownEditorV3Height.value = window.innerHeight - 70
});

// 监听路由参数
watch(
  () => route,
  (newValue, oldValue) => {
    console.log("EditPost页面的路由参数：newValue：", newValue)
    // console.log("newValue.path.indexOf('/postArticle')", newValue.path.indexOf("/postArticle"))
    // console.log("newValue.path.indexOf('/editArticle')", newValue.path.indexOf("/editArticle"))

    // 判断路由传递过来的参数，若为修改文章详情则需先获取对应文章内容
    // if (newValue.path.indexOf("/editArticle") != -1) {
    //   articleId.value = newValue.params.articleId
    //   getArticleDetail()
    // }
  },
  { immediate: true, deep: true }
)

onMounted(() => {
  // 获取一级板块和对应的二级板块
  getBoardList()

  // 查看当前是要更新文章还是发表文章
  console.log("查看是否更新文章", useUpdateArticleIdStore.getArticleId())
  if (useUpdateArticleIdStore.getArticleId() != null && useUpdateArticleIdStore.getArticleId() != '') {
    // 走到这里说明是更新文章
    editOrPostTag.value = 1
    // 回显文章详情
    getArticleDetail()
  }

  // console.log("onBeforeMount方法触发")
  // // 进入文章编辑页面，隐藏掉Header
  // const header = document.querySelector('#header')
  // if (header != null) {
  //   header.style.display = 'none'
  // }
})

onUnmounted(() => {
  console.log("离开文章编辑页面,onBeforeUnmount方法触发")
  // 离开文章编辑页面，清空store内容，防止下次进入该页面还是修改该文章
  useUpdateArticleIdStore.removeArticleId()
  //   // 离开文章编辑页面，显示Header
  //   const header = document.querySelector('#header')
  //   if (header != null) {
  //     header.style.display = 'block'
  //   }
})

// 查看当前form内容
const showArticleContent = () => {
  console.log(formData.value)
}
</script>

<template>
  <div class="edit-post">
    <el-form :model="formData" :rules="rules" ref="formDataRef" label-width="auto" class="post-panel">
      <!-- 左侧编辑器 -->
      <div class="post-editor">
        <!-- 导航区 -->
        <div class="banner">
          <!-- 左侧 返回主页 正文标题 -->
          <div class="title">
            <el-tooltip content="返回主页" placement="bottom" effect="light">
              <span class="iconfont icon-fanhui" @click="toHome"></span>
            </el-tooltip>
            <input class="title-input" type="text" placeholder="请输入文章标题..." v-model="formData.title">
          </div>
          <!-- 右侧 切换为富文本编辑器 发布文章 -->
          <div class="right-box">
            <!-- <div class="change-type" @click="changeEditorType">
              <span class="iconfont icon-change"></span>
              切换为{{ editorType == 0 ? "Markdown编辑器" : "富文本编辑器" }}
            </div> -->
            <div class="post-btn" @click=handleShowPostFialog>发布</div>
          </div>
        </div>
        <!-- 文章内容 -->
        <div class="post-container">
          <!-- 富文本编辑器 -->
          <!-- <HtmlEditor v-model="formData.content" v-if="editorType == 0" :height="HtmlEditorHeight"></HtmlEditor> -->
          <!-- Markdown编辑器 -->
          <!-- <MarkdownEditor v-model="formData.markdownContent" v-if="editorType == 1" @setHtmlContent="setHtmlContent"
            :height="markdownEditorHeight">
          </MarkdownEditor> -->
          <!-- md-editor-v3编辑器 -->
          <MarkdownEditorV3 ref="MarkdownEditorV3Ref" v-model="formData.markdownContent"
            :height="markdownEditorV3Height" @setHtmlContent="setHtmlContent" @setPreviewTheme="setPreviewTheme"
            @setCodeTheme="setCodeTheme">
          </MarkdownEditorV3>
        </div>
      </div>

      <!-- 发表文章前的配置信息 -->
      <el-dialog class="postArticleDialog" v-model="showPostDialog" title="Tips" :before-close="handleClosePostDialog">
        <div class="post-setting">
          <!-- 标题区 -->
          <div class="panel-title">发布文章</div>
          <div class="panel-detail">
            <!-- 文章板块 -->
            <el-form-item prop="boardIds" label="文章板块">
              <el-cascader placeholder="请选择文章所属板块" :options="boardList" :props="boardProps" clearable
                v-model="formData.boardIds" :style="{ width: '100%' }"></el-cascader>
            </el-form-item>
            <!-- 文章封面上传区 -->
            <el-form-item label="添加封面">
              <div class="upload-cover">
                <el-upload name="file" :multiple="false" :show-file-list="false"
                  accept=".png, .PNG, .jpg, .JPG, .jpeg, .JPEG, .gif, .GIF, .bmp, .BMP" :http-request="selectImg">
                  <div class="cover-img">
                    <div v-if="!coverImg" class="upload-cover-btn">
                      <span class="iconfont icon-add1"></span>
                    </div>
                    <img v-if="coverImg" :src="coverImg">
                    <!-- @click.stop 取消冒泡事件 -->
                    <span v-if="coverImg" class="iconfont icon-cancel" @click.stop="cancelSelectImg"></span>
                  </div>
                </el-upload>
              </div>
            </el-form-item>
            <!-- 文件摘要 -->
            <el-form-item label="文章摘要">
              <el-input placeholder="请输入文章摘要" v-model="formData.summary" type="textarea" :rows="5" :maxlength="150"
                resize="none" show-word-limit clearable></el-input>
            </el-form-item>
            <!-- 文章附件上传区 -->
            <el-form-item label="文章附件">
              <div class="upload-attachment">
                <el-upload v-if="!attachmentName" name="file" :multiple="false" :show-file-list="false"
                  accept=".zip, .rar" :http-request="selectAttachment">
                  <el-button type="success">添加附件</el-button>
                </el-upload>
                <div v-if="attachmentName" class="attachment-item">
                  <div class="attachment-name">{{ attachmentName }}</div>
                  <!-- <div>所需积分：0</div> -->
                  <div class="iconfont icon-cancel" @click="removeAttachment"></div>
                </div>
              </div>
            </el-form-item>

            <el-button type="success" v-loading="loadingRequest" style="width: 100%;"
              @click="postArticle">发布文章</el-button>
            <!-- <el-button type="success" style="width: 100%;" @click="showArticleContent">查看文章内容</el-button> -->
          </div>
        </div>
      </el-dialog>


    </el-form>
  </div>
</template>

<style>
.edit-post {
  width: 100%;
  background-color: #ddd;
  height: 100vh;
}

.edit-post .post-panel {
  display: flex;
  height: 100%;
}

/* 左侧编辑器 */
.edit-post .post-panel .post-editor {
  flex: 1;
}

/* 导航区 */
.edit-post .post-panel .post-editor .banner {
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 0 20px;
}

/* 左侧 返回主页 正文标题 */
.edit-post .post-panel .post-editor .banner .title {
  margin-left: 5px;
  color: #72767f;
}

.edit-post .post-panel .post-editor .banner .title .icon-fanhui {
  font-size: 30px;
  padding-right: 20px;
  cursor: pointer;
}

.edit-post .post-panel .post-editor .banner .title .title-input {
  border: none;
  outline: none;
  font-size: 24px;
  font-weight: 500;
  color: #1d2129;
  height: 100%;
  width: 1000px;
}

/* 右侧 切换为富文本编辑器 */
.edit-post .post-panel .post-editor .banner .right-box {
  display: flex;
  align-items: center;
}

.edit-post .post-panel .post-editor .banner .right-box .change-type {
  margin-right: 5px;
  color: #409EFF;
  cursor: pointer;
}

.edit-post .post-panel .post-editor .banner .right-box .post-btn {
  display: flex;
  align-items: center;
  background-color: rgb(4, 176, 4);
  height: 35px;
  font-size: 17px;
  border-radius: 2px;
  cursor: pointer;
  color: #fff;
  padding: 0 20px;
  margin-left: 10px;
}

/* 文章内容 */
.edit-post .post-panel .post-editor .post-container {
  text-align: start;
  background-color: blanchedalmond;
}

/* 发表文章前的配置信息 */
.postArticleDialog {
  margin-top: 70px;
  width: 600px !important;
}

.postArticleDialog .el-dialog__title {
  display: none;
}

.edit-post .post-panel .post-setting {
  background-color: #fff;
  /* max-height: calc(100vh - 100px); */
  /* 显示滚动条 */
  overflow: auto;
  margin-left: 10px;
}

.edit-post .post-panel .post-setting .panel-title {
  border-bottom: 1px solid #ededed;
  padding-bottom: 10px;
  font-size: 18px;
  color: #3c3c3c;
  margin-bottom: 10px;
  font-weight: 700;
}

.edit-post .post-panel .post-setting .panel-detail {
  padding: 10px 15px;
}

/* 文章封面上传区 */
.edit-post .post-panel .post-setting .panel-detail .upload-cover .cover-img {
  background-color: #fafafa;
  width: 150px;
  height: 150px;
  border-radius: 6px;
  border: 1px dashed #cdd0d6;
  overflow: hidden;

  /* 内容水平和垂直都居中 */
  display: flex;
  justify-content: center;
  align-items: center;

  position: relative;
}

.edit-post .post-panel .post-setting .panel-detail .upload-cover .cover-img:hover {
  border: 1px dashed #72767f;
}

.edit-post .post-panel .post-setting .panel-detail .upload-cover .cover-img .icon-add1 {
  color: #909399;
  font-size: 28px;
}

.edit-post .post-panel .post-setting .panel-detail .upload-cover .cover-img .icon-cancel {
  position: absolute;
  top: 5px;
  right: 5px;
  font-size: 20px;
  line-height: 20px;
}

.edit-post .post-panel .post-setting .panel-detail .upload-cover .cover-img img {
  width: 100%;
  object-fit: contain;
}

/* 文章附件上传区 */
.edit-post .post-panel .post-setting .panel-detail .upload-attachment {
  width: 100%;
}

.edit-post .post-panel .post-setting .panel-detail .upload-attachment .attachment-item {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.edit-post .post-panel .post-setting .panel-detail .upload-attachment .attachment-item .attachment-name {
  flex: 1;
  white-space: nowrap;
  text-overflow: ellipsis;
  color: #409EFF;
}

.edit-post .post-panel .post-setting .panel-detail .upload-attachment .attachment-item .icon-cancel {
  cursor: pointer;
}
</style>